//
//  PriceChooseViewController.m
//  House
//
//  Created by 张垚 on 16/8/12.
//  Copyright © 2016年 ZJWL. All rights reserved.
//

#import "PriceChooseViewController.h"
#import "BaseTitleNavigationBar.h"
#import "CustomPriceChooseTableViewCell.h"


@interface PriceChooseViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) BaseTitleNavigationBar *myBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *dataArr;
@property (nonatomic, strong) NSArray *submitArr;
@property (nonatomic, assign) NSInteger kbHeight;
@end

static NSString *cellID = @"PriceChooseViewControllerID";


@implementation PriceChooseViewController

- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = YES;
}

#pragma mark - 主程序入口
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    _kbHeight = 258.0;
    //本地数据 租房和二手房价格数据
    if (_tag == 100) {
        _dataArr = @[@"50万以下", @"50-100万", @"100-200万", @"200-300万", @"300万以上"];
        _submitArr = @[@"不限", @"0,50", @"50,100", @"100,200", @"200,300", @"300"];
    }else {
        _dataArr = @[@"1500元以下", @"1500元-2500元", @"2500元-3500元", @"3500元-4500元", @"4500元-5500元", @"5500元-6500元", @"6500元以上"];
        _submitArr = @[@"不限", @"0,1500", @"1500,2500", @"2500,3500", @"3500,4500", @"4500,5500", @"5500,6500", @"6500"];
    }
    /* 添加观察者 */
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [self initTableView];
    [self initNavigationBar];
    // Do any additional setup after loading the view.
}
#pragma mark - 顶部视图
- (void)initNavigationBar {
    _myBar = [[BaseTitleNavigationBar alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64) WithTitleStr:@"价格筛选"];
    [self.view addSubview:_myBar];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back)];
    [_myBar.leftView addGestureRecognizer:tap];
}
//返回上一层级
- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 键盘监听事件
- (void)keyboardWillShow:(NSNotification *)showNotification {
    /*获取键盘高度 中英文下高度是不同的 */
    CGFloat kbHeight = [[showNotification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    /* 将高度赋给属性 */
    _kbHeight = kbHeight;
    
}
- (void)keyboardWillHide:(NSNotification *)hideNotification {
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[hideNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _tableView.frame = CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height);
    }];
}

#pragma mark - tableview
//初始化 签协议
- (void)initTableView {
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64) style:UITableViewStylePlain];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    _tableView.scrollEnabled = NO;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[CustomPriceChooseTableViewCell class] forCellReuseIdentifier:NSStringFromClass([CustomPriceChooseTableViewCell class])];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
}
//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArr.count + 2;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //最后一个cell
    if (indexPath.row == _submitArr.count) {
       
        CustomPriceChooseTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([CustomPriceChooseTableViewCell class])];
        if ([_currentStr containsString:@"~"]) {
            NSArray *arr = [_currentStr componentsSeparatedByString:@"~"];
            cell.minPriceTextfield.text = [arr firstObject];
            cell.maxPriceTextfiled.text = [arr lastObject];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.sureButton.tag = indexPath.row;
        [cell.sureButton addTarget:self action:@selector(priceChoose:) forControlEvents:UIControlEventTouchUpInside];
        cell.minPriceTextfield.delegate = self;
        cell.maxPriceTextfiled.delegate = self;
        //二手房和租房单位不同 需要区分开
        if (_tag == 100) {
            cell.unitLabel.text = @"万";
        }else {
            cell.unitLabel.text = @"元";
        }
        return cell;
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
        }
        if (indexPath.row == 0) {
            cell.textLabel.text = @"不限";
        }
        else {
            //是否显示为红色文本
            if ([_currentStr isEqualToString:_dataArr[indexPath.row - 1]]) {
                cell.textLabel.textColor = KNaviBackColor;
            }
            cell.textLabel.text = _dataArr[indexPath.row - 1];
        }
        return cell;
    }
    
}
//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _submitArr.count) {
        
    }else {
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        _chooseInfoBlock(cell.textLabel.text, _submitArr[indexPath.row]);
        [self back];
    }
    
}
//行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ((kScreenHeight - 64) / (_dataArr.count + 2) >= 44) {
        return 44;
    }else {
        return (kScreenHeight - 64) / (_dataArr.count + 2);
    }
    
}

//私有方法
- (void)passInfoToPreviousPage:(chooseInfosBlock)infoBlock {
    _chooseInfoBlock = infoBlock;
}
#pragma mark - 自定义价格
//自定义价格 点击事件
- (void)priceChoose:(UIButton *)button {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:button.tag inSection:0];
    CustomPriceChooseTableViewCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
    if ([self isPureInt:cell.minPriceTextfield.text] && [self isPureInt:cell.maxPriceTextfiled.text]) {
        NSString *submitStr = [NSString stringWithFormat:@"%@,%@", cell.minPriceTextfield.text, cell.maxPriceTextfiled.text];
        NSString *showStr = [NSString stringWithFormat:@"%@~%@", cell.minPriceTextfield.text, cell.maxPriceTextfiled.text];
        if ([cell.minPriceTextfield.text integerValue] >= [cell.maxPriceTextfiled.text integerValue]) {
            [self alertMessage:@"最大价格必须大于最小价格"];
        }else {
            self.chooseInfoBlock(showStr, submitStr);
            [self back];
        }
    }else {
        [self alertMessage:@"自定义价格必须为整数"];
    }
}
//提示信息
- (void)alertMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
    [self presentViewController:alertController animated:YES completion:nil];
}


//判断是否为整数
- (BOOL)isPureInt:(NSString*)string{
    NSScanner *scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
#pragma mark - 代理协议
//点击return 收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

/* 即将开始编辑 键盘弹起 视图上移 */
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = textField.superview;
    while (![view isKindOfClass:[UITableViewCell class]]) {
        view = [view superview];
    }
    UITableViewCell *cell = (UITableViewCell*)view;
    CGRect rect = [cell convertRect:cell.frame toView:self.view];
    if (rect.origin.y / 2 + rect.size.height >= self.view.frame.size.height - _kbHeight) {
        [UIView animateWithDuration:0.25 animations:^{
            _tableView.frame = CGRectMake(0, -64, self.view.frame.size.width, self.view.frame.size.height);
        }];
    }
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
